#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>


#define BACKLOG 1


template<typename T>
int startServer(int port, volatile int * fd, volatile struct sockaddr_in * clientAddr,
                int (*callback)(volatile int * fd, volatile struct sockaddr_in * addr, socklen_t * len, T arg), T arg)
{
    int listenFd;
    struct sockaddr_in serverAddr;
    socklen_t clientAddrLen;

    listenFd = socket(AF_INET, SOCK_STREAM, 0);

    bzero(&serverAddr, sizeof(serverAddr));

    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serverAddr.sin_port = htons(port);

    bind(listenFd, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
    listen(listenFd, BACKLOG);

    for(;;)
    {
        clientAddrLen = sizeof(*clientAddr);
        *fd = accept(listenFd, (struct sockaddr *) clientAddr, &clientAddrLen);

printf("new client\n");

        if (callback)
        {
            while (*fd >= 0 && callback(fd, clientAddr, &clientAddrLen, arg) == 0);
        }

        while (*fd >= 0);
    }

    close(listenFd);

    return 0;
}
